import Taro, { Component, Config } from '@tarojs/taro'
import { Button, Form, Input, View } from '@tarojs/components'
import classNames from 'classnames'
import './index.scss'
import { getShopList } from '@/api/merchantApi'
import { getAddressList, getUserInfo } from '@/api/userApi'
import { asyncCalcOrder, getConnectUser, goToWechatPay, goToWalletPay, submitOrder } from '@/api/orderApi'
import lodash from '@/utils/lodash'
import { PAY_TYPE } from '@/config/types'
import {getShopCartGlobal, getFreightConfig, getBrand} from '@/utils/storage'
import OrderCardGoods from "@/components/order/cart-goods"
import { Loading, ShopSelect, CouponSelect, AddressSelect, WalletPay, ReserveSelect } from '@/components/index'
import { toOrderUnpaidPage, toOrderListPage } from '@/utils/page_router'
import { formatAmount, getSubscribeMessage } from '@/utils/utils'

const isSubmit = ({ payType, userInfo, orderInfo }) => {
  return (PAY_TYPE.WALLET === payType ? userInfo.amount >= orderInfo.payAmount : true)
}

//  获取地址
const getAddress = (list, info) => {
  if (info && info.id) {
    return info
  } else {
    const arr = list.filter(i => i.isDefault)
    return (arr.length >= 1 ? lodash.head(arr) : lodash.head(list))
  }
}
export default class Index extends Component {
  state: any

  config: Config = {
    backgroundTextStyle: "dark",
    navigationBarTextStyle: process.env.navigationBarTextStyle,
    navigationBarBackgroundColor: process.env.backgroundColor
  }

  constructor() {
    super(...arguments)
    this.state = {
      type: 0,
      typeList: [
        { title: '快递配送', value: 0 },
        { title: '到店自提', value: 1 }
      ],
      payType: PAY_TYPE.WECHAT,
      loading: true,
      isScore: false,
      orderInfo: {},
      showShop: false,
      isReserve: Number(getFreightConfig('reserveStatus')),
      showCoupon: false,
      showAddress: false,
      showReserve: false,
      showWallet: false,
      userInfo: {},
      shopInfo: {},
      couponInfo: {},
      addressInfo: null,
      connectSnap: {},
      appointTime: '',
      shopList: [],
      couponList: [],
      productList: [],
      addressList: [],
    }
  }

  componentDidMount () {
    this.initOrder()
    this.getConnectUser()
  }

  async componentDidShow() {
    const { loading, addressInfo } = this.state
    if (!loading) {
      Taro.showLoading({title: '请稍后', mask: true})
      const addressRes = await getAddressList()
      this.setState({
        addressInfo: getAddress(addressRes.data || [], addressInfo),
        addressList: addressRes.data || []
      }, () => {
        Taro.hideLoading()
      })
    }
  }

  //  初始化订单
  async initOrder() {
    const { addressInfo } = this.state
    const shopRes = await getShopList()
    const addressRes = await getAddressList()
    const userRes = await getUserInfo()
    this.setState({
      userInfo: userRes.data,
      shopInfo: lodash.head(shopRes.data),
      shopList: shopRes.data,
      addressInfo: getAddress(addressRes.data || [], addressInfo),
      addressList: addressRes.data || []
    }, () => {
      this.calcOrder()
    })
  }

  //  计算订单
  calcOrder() {
    const productList = getShopCartGlobal()
    const { params } = this.$router
    const { loading, addressInfo, couponInfo, orderInfo, isScore, type, typeList } = this.state
    const data:any = {
      id: orderInfo.id,
      distribute: typeList[type]['value'],
      productList,
      userCouponId: couponInfo.id,
      couponDiscount: couponInfo.amount,
      scoreDiscount: isScore ? orderInfo.deductScoreAmount : undefined
    }

    //  是否单独购买（团购商品）
    if (params.fullPay) {
      data.fullPay = params.fullPay
    }

    if (addressInfo) {
      data.cityCode = addressInfo.cityCode
    }

    if (!loading) {
      Taro.showLoading({title: '请稍后', mask: true})
    }
    asyncCalcOrder(data).then(res => {
      const { data } = res
      this.setState({
        orderInfo: data,
        couponList: data.couponList || [],
        productList: data.productList,
      }, () => {
        Taro.hideLoading()
        this.setState({
          loading: false
        })
      })
    })
  }

  //  获取自提记录填写的信息
  getConnectUser() {
    getConnectUser().then(res => {
      this.setState({
        connectSnap: res.data || {}
      })
    })
  }

  //  切换渲染类型
  onSwitchType(type) {
    this.setState({
      type
    }, () => {
      this.calcOrder()
    })
  }

  //  切换支付类型
  onSwitchPayType(type) {
    this.setState({
      payType: type
    })
  }

  //  开启积分
  openScore(bool) {
    this.setState({
      isScore: !bool
    }, () => {
      this.calcOrder()
    })
  }

  //  确认选择
  onConfirmSelect(name, info) {
    const { couponInfo } = this.state
    if (name === 'couponInfo') {
      info = (couponInfo.id === info.id) ? {} : info
    }
    this.setState({
      [name]: info
    }, () => {
      if((name === 'couponInfo' && couponInfo.id !== info.id) || name === 'addressInfo') {
        this.calcOrder()
      }
    })
  }

  // //  写入订单参数
  // setParams(object, callback?){
  //   const { orderParams } = this.state
  //   Object.keys(object).map(name => {
  //     orderParams[name] = object[name]
  //   })
  //   this.setState({
  //     orderParams
  //   }, () => {
  //     callback && callback()
  //   })
  // }

  //  提交表单
  onSubmit(e) {
    const { value } = e.detail
    const { params } = this.$router
    const { type, payType, orderInfo, addressInfo, shopInfo, couponInfo, appointTime } = this.state
    const data:any = {
      id: orderInfo.id,
      payType,
      userCouponId: couponInfo.id,
      couponDiscount: couponInfo.amount
    }
    Object.keys(value).map(name => {
      lodash.set(data, name, value[name])
    })

    if (type === 0 && !addressInfo) {
      Taro.showToast({ title: '请选择收货地址', icon: 'none' })
      return
    }

    if (type === 1 && !shopInfo) {
      Taro.showToast({ title: '请选择自提店铺', icon: 'none' })
      return
    }

    if (type === 1 && !data.connectSnap.name) {
      Taro.showToast({ title: '请输入联系人', icon: 'none' })
      return
    }

    if (type === 1 && !data.connectSnap.telephone) {
      Taro.showToast({ title: '请输入联系电话', icon: 'none' })
      return
    }

    //  非单独购买（团购商品）
    if (!params.fullPay && !!params.isPink) {
      Object.assign(data, {
        pinkId: params.pinkId ? params.pinkId : undefined,
        isPink: true
      })
    }

    //  配送方式
    if (type === 0) {
      Object.assign(data, {
        appointTime,
        addressSnap: addressInfo
      })
    }

    //  自提方式
    if (type === 1) {
      Object.assign(data, {
        cooperateShopId: shopInfo.id,
        cooperateShopAddress: shopInfo,
      })
    }

    //  订阅通知模板
    let tmplIds:any = type ? getSubscribeMessage('checkOrder') : getSubscribeMessage('postOrder')
    if (!!params.isPink) {
      tmplIds = tmplIds.concat(getSubscribeMessage('pinkOrder'))
    }
    Taro.requestSubscribeMessage({
      tmplIds,
      complete: () => {
        Taro.showLoading({title: '请稍后', mask: true})
        submitOrder(data).then(res => {
          if (payType === PAY_TYPE.WECHAT) {
            this.createMiniWechatAppPay(res.data)
          } else {
            Taro.hideLoading()
            this.setState({
              showWallet: true
            })
          }
        })
      }
    })
  }

  //  取消钱包支付
  onCancelWalletPay() {
    const { orderInfo } = this.state
    toOrderUnpaidPage(orderInfo.id, true)
  }

  //  确定钱包支付
  onConfirmWalletPay() {
    const { orderInfo } = this.state
    Taro.showLoading({ title: '请稍后', mask: true })
    goToWalletPay(orderInfo.id).then(() => {
      Taro.hideLoading()
      Taro.showToast({ title: '扣款成功', icon: 'success' })
      toOrderListPage(true)
    })
  }

  //  确认选择预订时间
  onConfirmReserve(time) {
    Taro.showLoading({ title: '请稍后', mask: true })
    this.setState({
      appointTime: time,
      showReserve: false
    }, () => {
      setTimeout(() => {
        Taro.hideLoading()
      }, 500)
    })
  }

  //  拉起支付
  createMiniWechatAppPay(orderId) {
    goToWechatPay(orderId).then(res => {
      let data = res.data
      Taro.requestPayment({
        ...data,
        success: function () {
          Taro.hideLoading()
          Taro.showToast({ title: '支付成功', icon: 'success', complete: function () {
              toOrderListPage(true)
            }
          })
        },
        fail: function () {
          Taro.hideLoading()
          Taro.showToast({ title: '支付取消', icon: 'none', complete: function () {
              toOrderUnpaidPage(orderId, true)
            }
          })
        }
      })
    })
  }


  render () {
    const {
      loading,
      type,
      typeList,
      payType,
      addressInfo,
      userInfo,
      shopInfo,
      isReserve,
      couponInfo,
      connectSnap,
      couponList,
      addressList,
      productList,
      shopList,
      showCoupon,
      showShop,
      showAddress,
      showReserve,
      showWallet,
      orderInfo,
      appointTime,
      isScore
    } = this.state
    const disabled = !isSubmit({ payType, userInfo, orderInfo })
    return (<View className='index'>
      {loading && <Loading isCover/>}
      <View className='index-scroll'>
        <View className='index-head delivery-type'>
          <View className='type-list d-f a-i-f-e'>
            {typeList.map((i, k) => {
              return (<View key={k} className={classNames('type-item d-f a-i-c j-c-c', { active: type === k })} onClick={this.onSwitchType.bind(this, k)}>{i.title}</View>)
            })}
          </View>
          {type == 0 && <View className='delivery-box d-f a-i-c j-c-b' onClick={this.setState.bind(this, { showAddress: true })}>
            {addressInfo && <View className='address-box'>
              <View className='base-address d-f a-i-c '>
                <View className='user-name t-o-e'>{addressInfo.name}</View>
                <View className='user-phone'>{addressInfo.telephone}</View>
              </View>
              <View className='address-text t-o-e-2'>{addressInfo.city} {addressInfo.detail}</View>
            </View>}
            {!addressInfo && <View className='address-box'>设置收货地址</View>}
            <View className='bnn-icon right-icon'>&#xe866;</View>
          </View>}
          {type == 1 && <View className='delivery-box d-f a-i-c j-c-b' onClick={this.setState.bind(this, { showShop: true })}>
            <View className='address-box'>
              <View className='base-address d-f a-i-c '>
                <View className='user-name t-o-e'>{shopInfo.shopName}</View>
                <View className='user-phone'>{shopInfo.phone}</View>
              </View>
              <View className='address-text t-o-e-2'>{shopInfo.address}</View>
            </View>
            <View className='bnn-icon right-icon'>&#xe866;</View>
          </View>}
        </View>

        <View className='order-card cart-list'>
          {productList.map((cart, key) => {
            return (<OrderCardGoods key={cart.id} info={cart} className={classNames('cart-item', {
              'thin-border__b': key < productList.length - 1
            })}/>)
          })}
        </View>
        <Form onSubmit={this.onSubmit.bind(this)}>
          <View className='order-card'>
            <View className='card-list'>
              {isReserve && type === 0 && <View className='list-item thin-border__b' onClick={this.setState.bind(this, { showReserve: true })}>
                <View className='item-left'>配送时间</View>
                <View className='item-right'>
                  {appointTime && <View className='t-o-e'>{appointTime}</View>}
                  {!appointTime && <View className='t-o-e placeholder-color'>不限时间</View>}
                  <View className='bnn-icon right-icon'>&#xe866;</View>
                </View>
              </View>}
              <View className='list-item thin-border__b' onClick={this.setState.bind(this, { showCoupon: true })}>
                <View className='item-left'>优惠券</View>
                <View className='item-right'>
                  {couponInfo.title && <View className='t-o-e'>{couponInfo.title}</View>}
                  {!couponInfo.title && <View className='t-o-e placeholder-color'>不使用</View>}
                  <View className='bnn-icon right-icon'>&#xe866;</View>
                </View>
              </View>
              {!!orderInfo.deductScoreAmount && <View className='list-item thin-border__b'>
                <View className='item-left'>可用{orderInfo.canDeductScore}{getBrand()}</View>
                <View className='item-right placeholder-color'>
                  抵用<View className='integral-num bnn-number'>￥{orderInfo.deductScoreAmount}</View>
                  <View className='check-box d-f a-s-c' onClick={this.openScore.bind(this, isScore)}>
                    {!isScore && <View className='unchecked-icon'/>}
                    {isScore && <View className='bnn-icon unchecked-icon check-icon'>&#xe645;</View>}
                  </View>
                </View>
              </View>}

              {type === 0 && <View className='list-item thin-border__b'>
                <View className='item-left'>快递费用</View>
                <View className='item-right bnn-number'>￥{orderInfo.freightAmount}</View>
              </View>}
              {type === 1 && <View className='list-item thin-border__b'>
                <View className='item-left'>联系人</View>
                <View className='item-right'>
                  <Input name='connectSnap.name' value={connectSnap.name} maxLength={16} placeholder='请填写您的联系姓名' className='item-input'/>
                </View>
              </View>}
              {type === 1 && <View className='list-item thin-border__b'>
                <View className='item-left'>联系电话</View>
                <View className='item-right'>
                  <Input name='connectSnap.telephone' type='number' value={connectSnap.telephone} maxLength={11} placeholder='请填写您的联系电话' className='item-input'/>
                </View>
              </View>}
              <View className='list-item f-w-w'>
                <View className='item-left'>备注信息</View>
                <View className='item-right'>
                  <Input name='remark' maxLength={255} placeholder='请添加备注（150字以内）' className='item-input'/>
                </View>
              </View>
            </View>
          </View>
          <View className='order-card'>
            <View className='total-list'>
              <View className='list-item'>
                <View className='item-left'>商品总价：</View>
                <View className='item-right bnn-number'>￥{formatAmount(orderInfo.productAmount)}</View>
              </View>
              <View className='list-item'>
                <View className='item-left'>运费：</View>
                <View className='item-right bnn-number'>￥{formatAmount(orderInfo.freightAmount)}</View>
              </View>
            </View>
          </View>
          <View className='order-card pay-type'>
            <View className='pay-title d-f a-i-c'>支付方式</View>
            <View className='type-list'>
              <View className={classNames('type-item', payType === PAY_TYPE.WECHAT && 'active')} onClick={this.onSwitchPayType.bind(this, PAY_TYPE.WECHAT)}>
                <View className='type-left f-g-5 thin-border__r'>
                  <View className='type-icon wechat-icon bnn-icon'>&#xe604;</View>
                  <View className='type-title'>微信支付</View>
                </View>
                <View className='type-right f-g-5'>微信便捷支付</View>
              </View>
              <View className={classNames('type-item', payType === PAY_TYPE.ALIPAY && 'active')} onClick={this.onSwitchPayType.bind(this, PAY_TYPE.ALIPAY)}>
                <View className='type-left f-g-5 thin-border__r'>
                  <View className='type-icon alipay-icon bnn-icon'>&#xe884;</View>
                  <View className='type-title'>支付宝支付</View>
                </View>
                <View className='type-right f-g-5'>支付宝便捷支付</View>
              </View>
              <View className={classNames('type-item', payType === PAY_TYPE.WALLET && 'active')} onClick={this.onSwitchPayType.bind(this, PAY_TYPE.WALLET)}>
                <View className='type-left f-g-5 thin-border__r'>
                  <View className='type-icon balance-icon bnn-icon'>&#xe6ec;</View>
                  <View className='type-title'>余额支付</View>
                </View>
                <View className='type-right f-g-5 bnn-number'>可用余额 {userInfo.amount}</View>
              </View>
            </View>
          </View>
          <View className='index-foot--height'/>
          <View className='index-foot d-f a-i-c fy-popup fy-popup--bottom'>
            <View className='total-num'>共{productList.length}件</View>
            <View className='total-money d-f j-c-e'>合计：<View className='money-num bnn-number'>￥{formatAmount(orderInfo.payAmount)}</View></View>
            <Button disabled={disabled} formType="submit" className='buy-now d-f a-i-c j-c-c' hoverClass='hover-class--btn'>提交订单</Button>
          </View>
        </Form>
      </View>
      <WalletPay
        amount={orderInfo.payAmount}
        isOpened={showWallet}
        onCancel={this.onCancelWalletPay.bind(this)}
        onConfirm={this.onConfirmWalletPay.bind(this)}
      />
      {isReserve && <ReserveSelect
        value={appointTime}
        isOpened={showReserve}
        onClose={this.setState.bind(this, { showReserve: false })}
        onConfirm={this.onConfirmReserve.bind(this)}/>}
      <ShopSelect isOpened={showShop} item={shopInfo} list={shopList} onClose={this.setState.bind(this, { showShop: false })} onConfirm={this.onConfirmSelect.bind(this, 'shopInfo')}/>
      <AddressSelect isOpened={showAddress} item={addressInfo} list={addressList} onClose={this.setState.bind(this, { showAddress: false })} onConfirm={this.onConfirmSelect.bind(this, 'addressInfo')}/>
      <CouponSelect isOpened={showCoupon} item={couponInfo} list={couponList} onClose={this.setState.bind(this, { showCoupon: false })} onConfirm={this.onConfirmSelect.bind(this, 'couponInfo')}/>
    </View>)
  }
}
